package controller;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import validation.InputValidation;

import bizlogic.PriorityManager;
import model.PriorityDTO;

/**
 * Servlet implementation class ProcessPriorityServlet
 */
@WebServlet("/ProcessPriorityServlet")
public class ProcessPriorityServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ProcessPriorityServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

	private void processRequest(HttpServletRequest request,HttpServletResponse response)
	{
		RequestDispatcher rd;
		PriorityManager pm = new PriorityManager();
		PriorityDTO pDTO = new PriorityDTO();
		String status = InputValidation.ValidatePriority(request.getParameter("code"), request.getParameter("level"));

		if (status == "")
		{
			pDTO.setCode(Integer.parseInt(request.getParameter("code")));		
			pDTO.setLevel(request.getParameter("level"));
			String ins = (String)request.getParameter("ins");
			if(ins.equalsIgnoreCase("true"))
			{
				pm.insertPriority(pDTO);
			}else{
				pm.updatePriority(pDTO);
			}
			ArrayList<PriorityDTO> pData = pm.findAllPriority();
			request.setAttribute("priority", pData);	
			rd = request.getRequestDispatcher("ShowPriority.jsp");
		}			
		else
		{
			request.setAttribute("errormessage", status);	
			rd = request.getRequestDispatcher("ManagePriority.jsp");
		}		
	
		try{
			rd.forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}	
}
